package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    public static void main(String[] args) {
        System.out.println(mapping);
        MethodMapping mm =mapping.get("/myweb/reg");
        System.out.println(mm);
    }
    private static Map<String,MethodMapping> mapping = new HashMap<>();

    static{
        initMapping();
    }

    private static void initMapping(){
        try{
            File dir = new File(
                    HandlerMapping.class.getClassLoader().
                            getResource("./com/webserver/controller").toURI());

            String packageName = "com.webserver."+dir.getName();

            File[] files = dir.listFiles();
            for(File file : files){
                String className = file.getName().substring(0,file.getName().indexOf("."));
                Class cls = Class.forName(packageName+"."+className);
                if(cls.isAnnotationPresent(Controller.class)){
                    Object controller = cls.newInstance();
                    Method[] methods = cls.getDeclaredMethods();
                    for(Method method : methods){
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String path = rm.value();
                            MethodMapping methodMapping = new MethodMapping(controller,method);
                            mapping.put(path,methodMapping);
                        }
                    }
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static MethodMapping getMethod(String path){
        return mapping.get(path);
    }

    public static class MethodMapping{
        private Object controller;
        private Method method;

        public MethodMapping(){

        }

        public MethodMapping(Object controller,Method method){
            this.controller = controller;
            this.method = method;
        }

        public Object getController() {
            return controller;
        }

        public Method getMethod() {
            return method;
        }
    }
}
